class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution(object):
    def bstFromPreorder(self, preorder):
        root = TreeNode(preorder[0])
        st = [root]
        for num in preorder[1:]:
            new_node = TreeNode(num)
            if num < st[-1].val:
                st[-1].left = new_node
            else:
                while len(st) >= 2 and st[-2].val < num:
                    st.pop()
                node = st.pop()
                node.right = new_node
                st.append(new_node)
        return root


